package com.zqr.interrupted;

/**
 * @author zqr
 * @since 2022/11/4
 */
public class InterruptedDemo01 {
    public static void main(String[] args) {
        test2();
    }

    // 测试1，不通过中断异常结束，只是改变标志位
    public static void test1() {
        Thread t1 = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("运行中...");
            }
            System.out.println("线程结束运行");
        });
        t1.start();
        // 3秒后中断
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
    }

    // 测试2 通过中断异常中断线程
    public static void test2() {
        boolean flag = true;
        Thread t1 = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Thread.sleep(1000);
                    System.out.println("睡一秒。。。");
                } catch (InterruptedException e) {
                    System.out.println("收到了异常中断，当前的中断标志位:" + Thread.currentThread().isInterrupted()); // 收到异常的时候被复位了，为false
//                    System.out.println("收到信号了但是还想继续睡");
                    Thread.currentThread().interrupt(); //自己打断自己
                    System.out.println(Thread.interrupted()); //用静态方法判断，现在是true
                    System.out.println(Thread.currentThread().isInterrupted()); // 现在是false
                    Thread.currentThread().interrupt(); //再次打断自己，退出循环
                }
            }
            System.out.println("退出循环");
        });
        t1.start();
        try {
//            Thread.sleep(2000);
            Thread.sleep(1500);
            t1.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
